package com.xaicode.learn.netty.heartbeat;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Locker xaicode@sina.com
 * @version 1.0
 * @date 2021/6/19 0019 21:46
 */
@Slf4j
public class HeartBeatServerHandler extends ChannelInboundHandlerAdapter {

    // Gets called if an user event was triggered.
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

        if (evt instanceof IdleStateEvent) {
            // cast
            IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
            // idle state check
            String state = "";
            switch (idleStateEvent.state()) {
                case READER_IDLE:
                    state = "No data was received for a while";
                    break;
                case WRITER_IDLE:
                    state = "No data was sent for a while";
                    break;
                case ALL_IDLE:
                    state = "No data was either received or sent for a while";
                    break;
            }
            log.info("client [{}] idle state is [{}]", ctx.channel().remoteAddress(), state);
        }

    }
}
